<template>
  <div class="init-container">
    <div class="mask-container" v-if="isMask"></div>
    <div class="flybar-settings">
      <!-- 基础设置 -->
      <Card class="settings-card">
        <div slot="title" class="section-title">
          <h3>基础设置</h3>
        </div>
        <div class="row-base">
          <div class="col-form">
            <Form label-position="left" :label-width="150">
              <FormItem :label="baseSettings.rotationArcTeeth.label">
                <InputNumber
                  v-model="baseSettings.rotationArcTeeth.value"
                  :min="0"
                  :max="32767"
                  :step="1"
                  @on-blur="
                    handleParamChange(
                      'rotationArcTeeth',
                      baseSettings.rotationArcTeeth.code,
                      baseSettings.rotationArcTeeth.value
                    )
                  "
                ></InputNumber>
              </FormItem>
              <FormItem :label="baseSettings.reversalInterval.label">
                <InputNumber
                  v-model="baseSettings.reversalInterval.value"
                  :min="0"
                  :max="3000"
                  :step="1"
                  @on-blur="
                    handleParamChange(
                      'reversalInterval',
                      baseSettings.reversalInterval.code,
                      baseSettings.reversalInterval.value
                    )
                  "
                ></InputNumber>
              </FormItem>
            </Form>
          </div>
          <div class="col-form">
            <Form label-position="left" :label-width="150">
              <FormItem :label="baseSettings.rotationArcTime.label">
                <InputNumber
                  v-model="baseSettings.rotationArcTime.value"
                  :min="0"
                  :max="3000"
                  :step="1"
                  @on-blur="
                    handleParamChange(
                      'rotationArcTime',
                      baseSettings.rotationArcTime.code,
                      baseSettings.rotationArcTime.value
                    )
                  "
                ></InputNumber>
              </FormItem>
              <FormItem :label="baseSettings.rotationDelay.label">
                <InputNumber
                  v-model="baseSettings.rotationDelay.value"
                  :min="0"
                  :max="3000"
                  :step="1"
                  @on-blur="
                    handleParamChange(
                      'rotationDelay',
                      baseSettings.rotationDelay.code,
                      baseSettings.rotationDelay.value
                    )
                  "
                ></InputNumber>
              </FormItem>
            </Form>
          </div>
        </div>
      </Card>

      <!-- 槽位设置 -->
      <Card class="settings-card">
        <div slot="title" class="section-title">
          <h3>转动齿数/时间设定</h3>
        </div>
        <div class="row-tank">
          <div
            class="col-tank"
            v-for="(tank, index) in tankSettings"
            :key="index"
          >
            <Card class="tank-card">
              <div slot="title" class="tank-title">{{ tank.name }}</div>
              <Form label-position="left" :label-width="150">
                <FormItem :label="tank.settings.teethCount.label">
                  <InputNumber
                    v-model="tank.settings.teethCount.value"
                    :min="0"
                    :max="3000"
                    :step="1"
                    @on-blur="
                      handleTankChange(
                        tank.id,
                        'teethCount',
                        tank.settings.teethCount.code,
                        tank.settings.teethCount.value
                      )
                    "
                  ></InputNumber>
                </FormItem>
                <FormItem :label="tank.settings.timingSetting.label">
                  <InputNumber
                    v-model="tank.settings.timingSetting.value"
                    :min="0"
                    :max="3000"
                    :step="1"
                    :disabled="true"
                  ></InputNumber>
                </FormItem>
              </Form>
            </Card>
          </div>
        </div>
      </Card>
    </div>
  </div>
</template>

<script lang="ts">
import {
  Tsrv,
  T_srv,
  ifs,
  ts,
  vue,
  I_cmd,
  T_cmd,
  tankSettings,
  baseSettings,
  N_FeibaRSet
} from './config';

@T_srv.comp
export default class cFeibaRSet extends vue {
  /* 父组件compBoxInfo */
  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  compBoxInfo: ifs.I_compBoxInfo;

  /* 组件名 */
  private name: string = 'cFeibaRSet';

  private G_compName: string = this.name;

  /* 组件箱信息对象 */
  private GT_compBoxInfo: ifs.I_compBoxInfo;

  /* 组件箱对象 */
  private GT_compBox: ifs.I_compBox;

  /* 组件箱识别ID */
  private G_compID: string;

  /* 指挥部 */
  private GT_command: I_cmd = new T_cmd();

  /* 遮罩 */
  public isMask: boolean = false;

  public codes: string[] = [];

  private baseSettings: N_FeibaRSet.BaseSettings = baseSettings();

  private tankSettings: Array<N_FeibaRSet.TankConfig> = tankSettings();

  private copyBaseSettings: N_FeibaRSet.BaseSettings;

  private copyTankSettings: Array<N_FeibaRSet.TankConfig>;

  created() {
    // 如果父组件没有传参，那就产生一个
    this.GT_compBoxInfo = Tsrv.getCompInfo(this.compBoxInfo);
    this.G_compID = this.GT_compBoxInfo.compID;
    this.GT_compBox = this.GT_compBoxInfo.TcompBox;
    this.GT_command.init(this, this.GT_compBoxInfo);
    this.copyBaseSettings = Tsrv.utils.clone(this.baseSettings, true);
    this.copyTankSettings = Tsrv.utils.clone(this.tankSettings, true);
  }

  mounted() {
    /* 向父组件发送实例 */
    this.GT_compBox.addCompMergeName(this.G_compID, this.G_compName, this);
    this.$emit('compBoxInfo', this.GT_compBoxInfo);
    this.init();
    this.GT_command.startTask();
    this.receiveEvent();
  }

  private receiveEvent() {
    this.$bus.$on(
      '__PLC_CONNSTATE__',
      (data: { connState: boolean; ecBoxName: string }) => {
        if (data.ecBoxName === 'mianyang') {
          if (data.connState) {
            if (!this.GT_command.isOpenTask) {
              this.GT_command.startTask();
            }
          } else {
            this.GT_command.stopTask();
          }
        }
      }
    );
  }

  destroyed() {
    /* 注册组件销毁 */
    this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName);
    this.$bus.$off('__PLC_CONNSTATE__');

    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox.removeCompsWithCompID(this.G_compID);
    } else {
      this.GT_compBox.removeCompsMergeName(this.G_compID, [
        `'${this.G_compName}'`
      ]);
    }
    /* 如果是动态组件可能会关闭全局compBox */
    // this.GT_compBox = null
  }

  /* 设置组件整体遮罩 */
  public setMask(p: boolean) {
    this.isMask = p;
  }

  public getMask(p: boolean): boolean {
    return this.isMask;
  }

  // 初始化读取点位信息，显示plc值
  private init() {
    this.codes = [];
    Object.keys(this.baseSettings).forEach(key => {
      this.codes.push(this.baseSettings[key].code);
    });

    this.tankSettings.forEach(tank => {
      Object.keys(tank.settings).forEach(key => {
        this.codes.push(tank.settings[key].code);
      });
    });
  }

  private updateSettings(data: ifs.I_scadaReadResp['data']) {
    Object.keys(this.baseSettings).forEach(key => {
      const code = this.baseSettings[key].code;
      if (data[code]) {
        this.baseSettings[key].value = data[code].v;
      }
    });

    this.tankSettings.forEach(tank => {
      Object.keys(tank.settings).forEach(key => {
        const code = tank.settings[key].code;
        if (data[code]) {
          tank.settings[key].value = data[code].v;
        }
      });
    });
  }

  public updateData() {
    Tsrv.readPlcData(this.codes).then(res => {
      if (typeof res !== 'boolean') {
        // 更新设定值
        this.updateSettings(res);
      }
    });
  }

  private handleParamChange(
    path: keyof N_FeibaRSet.BaseSettings,
    code: string,
    value: number
  ) {
    if (this.copyBaseSettings[path].value === value) return;
    this.copyBaseSettings[path].value = value;
    // 处理参数变更逻辑
    Tsrv.writePlcData([{ ecDetCode: code, value: value.toString() }]).then(
      success => {
        if (success) {
          this.$Message.success('写入成功');
          this.init();
        }
      }
    );
  }

  private handleTankChange(
    tankId: string,
    param: keyof N_FeibaRSet.TankConfig,
    code: string,
    value: number
  ) {
    let flag = true;
    // 处理槽位参数变更逻辑
    this.copyTankSettings.forEach(tank => {
      if (tank.id === tankId) {
        if (tank.settings[param].value === value) {
          flag = false;
        } else {
          flag = true;
          tank.settings[param].value = value;
        }
      }
    });
    if (flag) {
      Tsrv.writePlcData([{ ecDetCode: code, value: value.toString() }]).then(
        success => {
          if (success) {
            this.$Message.success('写入成功');
            this.init();
          }
        }
      );
    }
  }
}
</script>

<style lang="scss" scoped>
$base-gap: 24px !default; // 主间距
$breakpoints: (
  mobile: 768px,
  tablet: 1200px
); // 响应式断点

@mixin flex-layout($gap: $base-gap, $wrap: wrap) {
  display: flex;
  flex-wrap: $wrap;
  margin: -($gap/2);
  > * {
    padding: $gap/2;
  }
}

.flybar-settings {
  padding: 20px;

  .settings-card {
    margin-bottom: $base-gap;

    .row-base {
      @include flex-layout(row, $base-gap);
      margin: -($base-gap / 2);

      .col-form {
        flex: 1;
        padding: $base-gap / 2;
        min-width: 300px;
      }
    }

    .row-tank {
      @include flex-layout(row, $base-gap);
      flex-wrap: wrap;
      margin: -($base-gap / 2);

      .col-tank {
        flex: 0 0 calc(33.333% - #{$base-gap});
        margin: $base-gap / 2;
        min-width: 280px;

        @media (max-width: 1200px) {
          flex-basis: calc(50% - #{$base-gap});
        }

        @media (max-width: 768px) {
          flex-basis: 100%;
        }
        .tank-title {
          font-weight: 500;
          font-size: 14px;
        }
      }
    }

    ::v-deep .ivu-card-head {
      background: #f8f8f9;
      padding: 16px 24px;
    }

    .section-title {
      text-align: center;

      h3 {
        font-size: 18px;
        color: #17233d;
        margin: 0;
      }
    }

    .tank-card {
      margin: 8px;

      .tank-title {
        font-weight: 500;
        color: #2d8cf0;
      }

      ::v-deep .ivu-input-number {
        width: 100%;
      }
    }
  }
}
</style>
